source ./pubfunc.sh

#if ! $(ip_exists "10.45.80.190")
#then
#    exit
#fi

if [ ! -d /tmp/zlogs ]
then
    print_info "skip"
    exit
fi

cd /tmp/zlogs
ls| while read PATH_PROD
do
    if [ -d ${PATH_PROD} ]
    then
        cd ${PATH_PROD}
        PATH_SIZE=0
        DKER_LIST=$(ls -tr)
        PATH_SIZE=$(echo "${DKER_LIST}"|wc -l)
        if [ ${PATH_SIZE} -gt 100 ]
        then
            print_error "too many docker log paths, some docker maybe restart quickly, try protection"
            TO_DELETE_DKER_LIST=$(echo "${DKER_LIST}"|head -$(expr ${PATH_SIZE} - 10)|tail -$(expr ${PATH_SIZE} - 20))
            for PATH_DKER in ${TO_DELETE_DKER_LIST}
            do
              DKER_ID=$(docker ps --filter "id=${PATH_DKER}" --format "{{.ID}}")
              if [ ${DKER_ID}"x" = "x" ]
              then
                  rm -r ${PATH_DKER}
              fi
            done
        fi
        for PATH_DKER in ${DKER_LIST}
        do
          if [ -d ${PATH_DKER} ]
          then
              DKER_ID=$(docker ps --filter "id=${PATH_DKER}" --format "{{.ID}}")
              if [ ${DKER_ID}"x" = "x" ]
              then
                  for file2del in $(find ${PATH_DKER} -mtime +3 -type f)
                  do
                      if [ $(fuser $file2del)"x" = "x" ]
                      then
                          rm $file2del
                      fi
                  done
                  if [ $(find ${PATH_DKER} -type f |wc -l) -eq 0 ]
                  then
                     rm -r ${PATH_DKER}
                  fi
              fi
          fi
          PATH_SIZE=$(expr ${PATH_SIZE} + 1)
        done
    fi
    cd /tmp/zlogs
done

clean_bigfile()
{
    FS_PCT=$(df /tmp/zlogs 2>/dev/null |tail -1|awk '{print int($5)}')
    if [ ${FS_PCT} -gt $1 ]
    then
          for BIG_FILE in $(find /tmp/zlogs -type f -size +${2}M)
          do
           > ${BIG_FILE}
          done
    fi
}

FS_PCT=$(df /tmp/zlogs 2>/dev/null |tail -1|awk '{print int($5)}')
if [ ${FS_PCT} -gt 85 ]
then
    print_error "filesystem nearly full, try protection"
    clean_bigfile 90 5120
    clean_bigfile 75 500
    clean_bigfile 75 50
    clean_bigfile 75 10
fi
